<template>
  <div class="main ad-manage-edit">
    <el-form class="section" :model="formData" :rules="formRules" size="medium" ref="form" label-width="150px">
      <el-form-item label="广告位置:" v-if="postionType!=='ICON'" prop="position">
        <el-select v-model="formData.position" filterable clearable>
          <el-option v-for="item in positionList" :key="item.position" :label="item.title" :value="item.position"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题:" prop="title">
        <el-input v-model="formData.title" :maxlength="postionType=== 'ICON'? 4 : 10"></el-input>
      </el-form-item>
      <el-form-item label="起止时间:" v-if="postionType!=='ICON'" prop="dateTimeRange">
        <el-date-picker v-model="formData.dateTimeRange" type="datetimerange" range-separator="~" value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="上传图片:" prop="imageUrl">
        <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false"
          :on-success="(res)=>{formData.imageUrl = replaceImgUrl(res.filePath)}" :before-upload="beforeUploadAd">
          <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="跳转类型:" prop="linkType">
        <el-radio v-for="(item, index) in jumpTypes" v-model="formData.linkType" :label="item.val" :key="index">{{item.name}}</el-radio>
      </el-form-item>
      <el-form-item label="跳转URL:" prop="linkUrl" v-if="formData.linkType === 'LINK_URL'">
        <el-input v-model="formData.linkUrl" placeholder="http(s)://"></el-input>
      </el-form-item>
      <template v-if="formData.linkType === 'LINK_INNER'">
        <el-form-item label="内页类型:" prop="targetType">
          <el-radio @change="changeTargetType" v-for="(item, index) in innerPageType" v-model="formData.targetType" :label="item.code" :key="index">
            {{item.desc}}</el-radio>
        </el-form-item>
        <template v-if="formData.targetType === 'GOODS_BIXUAN' || formData.targetType ==='MAKE_MONEY'">
          <el-form-item label="内页内容:" prop="type">
            <template v-if="formData.targetType === 'GOODS_BIXUAN'">
              <el-radio v-for="(item, index) in bxGoodsType" v-model="formData.inpageType" :label="item.val" :key="index" @change="changeBxGoodsType">
                {{item.name}}</el-radio>
            </template>
            <template v-if="formData.targetType === 'MAKE_MONEY'">
              <el-radio v-for="(item, index) in openBusinessType" v-model="formData.inpageType" :label="item.val" :key="index">{{item.name}}
              </el-radio>
            </template>
          </el-form-item>
        </template>
        <el-form-item v-else-if="formData.targetType === 'TUANYOU'" label="URL:" prop="adLinkObject.targetValue">
          <el-input v-model="formData.adLinkObject.targetValue" placeholder="http(s)://"></el-input>
        </el-form-item>
      </template>
      <el-form-item :label="`跳转:`" v-if="(formData.targetType !=='MAKE_MONEY'&&formData.targetType!=='ZERO_BUY_BIHUASUAN'&&formData.targetType!=='TUANYOU') && formData.linkType =='LINK_INNER'" prop="adLinkObject.title">
        <span>{{formData.adLinkObject.title}}</span>
        <el-button type="primary" plain @click="chooseJump">请选择</el-button>
      </el-form-item>
      <el-form-item label="跳转方式:" v-if="formData.targetType ==='TAOBAO_ACTIVITY'&&taobaoSelect.length>0&&formData.linkType === 'LINK_INNER'">
        <el-radio v-model="formData.gotoWay" :label="0" >直接跳转淘宝</el-radio>
        <el-radio v-model="formData.gotoWay" :label="1" :disabled="radioDisabled">跳转活动中间页</el-radio>
      </el-form-item>
      <el-form-item v-if="formData.position === 'BANNER_HOME_POP_UP_WINDOW'" label="指定用户:" prop="useCondition">
        <el-radio  v-model="formData.useCondition" label="0" @change="changeValidate">不限制</el-radio><br/>
        <el-radio  v-model="formData.useCondition" label="1" @change="changeValidate">指定</el-radio>
        <template v-if="formData.useCondition==='1'">
          <div class="use-type-block">
            <el-checkbox v-model="formData['BY_USER_NEW']">用户类型：</el-checkbox>
            <el-checkbox-group :disabled="!formData['BY_USER_NEW']" v-model="userType" @change="setUserType">
              <el-checkbox label="1" :key="1">纯分享购</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="use-type-block">
            <!-- <span>用户等级：</span> -->
            <el-checkbox v-model="formData['BY_USER_TYPE']">用户等级：</el-checkbox>
            <el-checkbox-group :disabled="!formData['BY_USER_TYPE']" v-model="tempUserLevels" @change="setUserLevels">
              <el-checkbox label="0" :key="0">普通用户</el-checkbox>
              <el-checkbox label="1" :key="1">兰蜜</el-checkbox>
              <el-checkbox label="2" :key="2">大区</el-checkbox>
              <el-checkbox label="3" :key="3">董事</el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-switch v-model="formData.enabled" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" :active-value="1"
          :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="排序:" prop="sort">
        <el-input-number v-model="formData.sort" style="text-align:left" :controls="false" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="success" :loading="btnLoading" @click="save">保存</el-button>
        <el-button type="info" plain @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  getPosition,
  saveAdSetting,
  getAdDetail,
  getAdTypes
} from '@/api/bihuasuan/ad'
import { getFavorSubjec } from '@/api/bihuasuan/goods'
import { regexp } from '../../../../utils/tools'
import { tbActivityGet } from '@/api/bihuasuan/taobaoActivity'
export default {
  name: 'b-adManageEdit',
  data() {
    return {
      innerPageType: [],
      postionType: '',
      positionList: [], // 广告位列表
      //碧选商品内页内容
      bxGoodsType: [
        { name: '商品', val: 1 }
        // { name: '套餐', val: 2 }
      ],
      bhsGoodsId: '', // 碧划算商品Id
      openBusinessType: [{ name: '开启创业页', val: 'MAKE_MONEY' }],
      jumpTypes: [
        { name: '无', val: 'NONE' },
        { name: 'URL', val: 'LINK_URL' },
        { name: '内页', val: 'LINK_INNER' }
      ], // 跳转类型
      pageTypes: [
        { name: '碧选商品', val: 'GOODS_BIXUAN' },
        { name: '碧划算商品', val: 'GOODS_BIHUASUAN' },
        { name: '开启创业', val: 'MAKE_MONEY' },
        { name: '碧划算商品栏目', val: 'TAG_TOPIC' },
        { name: '碧划算平台', val: 'PLATFORM_BIHUASUAN' },
        { name: '团油', val: 'TUANYOU' }
      ],
      btnLoading: false,
      userType: [],
      tempUserLevels: [],
      formData: {
        id: null,
        position: '',
        title: '',
        inpageType: 1,
        dateTimeRange: [],
        startTime: '',
        endTime: '',
        imageUrl: '',
        linkType: 'NONE',
        type: 'ICON',
        enabled: 1,
        sort: '',
        targetType: 'GOODS_BIXUAN',
        linkUrl: '',
        gotoWay:1,
        adLinkObject: {
          fromType: '',
          goodsType: '',
          goodsUrl: '',
          packType: '',
          targetType: '',
          targetValue: '',
          title: '',
          imageUrl: ''
        },
        useCondition: '0',
        adPermission: {
          newUser: false,
          roleIds: []
        }
      },
      taobaoSelect:[],
      radioDisabled: false,
      formRules: {
        position: [{ required: true, message: '请选择', trigger: 'change' }],
        title: [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        dateTimeRange: [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        imageUrl: [{ required: true, message: '不能为空', trigger: 'change' }],
        // adCode: [{ required: true, message: '不能为空', trigger: 'change' }],
        linkUrl: [
          { required: true, message: '不能为空', trigger: 'change' },
          { pattern: regexp.url, message: '格式错误', trigger: 'change' }
        ],
        targetType: [
          { required: true, message: '请选择内页类型', trigger: 'change' }
        ],
        linkType: [
          { required: true, message: '请选择指定类型', trigger: 'change' }
        ],
        sort: [{ required: true, message: '不能为空', trigger: 'change' }],

        'adLinkObject.title': [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.init()
  },
  watch: {
    'formData.targetType'(val) {
      if (val === 'MAKE_MONEY') {
        this.formData.inpageType = val
      }
      if (val === 'GOODS_BIXUAN') {
        this.formData.inpageType = 1
      }
      if (val === 'GOODS_BIHUASUAN' && !this.bhsGoodsId) {
        this.getBhsGoodId()
      }
    }
  },
  methods: {
    init() {
      this.postionType = this.$route.params.type
      this.formData.type = this.$route.params.type
      if (this.postionType === 'ICON') {
        this.formData.position = 'ICON_HOME_TOP'
      }
      if (this.$route.params.id) {
        this.id = this.$route.params.id
        // console.log("id", this.id);
        this.fetchData()
      } else {
        this.id = null
      }
      this.fetchAdPositionData()
      this._getAdTypes() // 获取内页类型
    },
    async _getAdTypes() {
      try {
        const { data } = await getAdTypes()
        this.innerPageType = data
        // console.log('!@!', data)
      } catch (error) {
        console.log(error)
      }
    },
    async fetchData() {
      try {
        const { data } = await getAdDetail({ id: this.id })
        const result = {
          ...data,
          dateTimeRange: [data.startTime, data.endTime],
          inpageType: (data.adLinkObject && data.adLinkObject.goodsType) || '',
          adLinkObject:data.adLinkObject === null? {
                  fromType: '',
                  goodsType: '',
                  goodsUrl: '',
                  packType: '',
                  targetType: '',
                  targetValue: '',
                  title: '',
                  imageUrl: ''
                }: data.adLinkObject,
          linkUrl:data.linkType === 'LINK_URL' ? data.adLinkObject.targetValue : '',
          targetType:data.linkType === 'LINK_INNER'? data.adLinkObject.targetType: 'GOODS_BIXUAN',
          gotoWay:data.gotoWay?data.gotoWay:0,
          useCondition: data.adPermission === null ? '0' : '1'
        }
        if(data.adPermission){
          if(data.adPermission.newUser){
            result['BY_USER_NEW'] = true
            this.userType = ['1']
          }
          if(data.adPermission.roleIds){
            result['BY_USER_TYPE'] = true
            this.userType = ['1']
            result.adPermission.roleIds = data.adPermission.roleIds.map(i => i.toString())
            this.tempUserLevels = result.adPermission.roleIds
          }
        }
        this.formData = result
        if (data.targetType === 'TAG_ACTIVITY') {
          this.formData.targetType = 'TAG_TOPIC'
        }
        if(data.adLinkObject.targetType === 'TAOBAO_ACTIVITY') {
          this.taobaoSelect=[{...data.adLinkObject, id:data.adLinkObject.targetValue, centerPage:data.gotoWay, activityName:data.adLinkObject.title}]
          let idd = data.adLinkObject.targetValue
          tbActivityGet({id:idd}).then((res) =>{
            if(res.data.centerPage ===0) {
              this.radioDisabled = true
            } else {
              this.radioDisabled = false
            }
          })
          console.log(data)
        } else {
          this.taobaoSelect = []
        }
        console.log(this.formData)
        console.log(this.taobaoSelect)
      } catch (error) {
        console.log(error)
      }
    },
    async fetchAdPositionData() {
      try {
        const { data } = await getPosition({ type: this.postionType })
        this.positionList = data.list || []
      } catch (error) {
        this.positionList = []
      }
    },
    setUserLevels() {
      if(this.formData.adPermission === '' || this.formData.adPermission === null ){
        this.formData.adPermission = Object.assign({}, {
          newUser: (this.userType.length>0),
          roleIds: Object.assign([], this.tempUserLevels)
        })
      } else {
        this.formData.adPermission.roleIds = Object.assign([], this.tempUserLevels)
      }
    },
    setUserType(val) {
      if(this.formData.adPermission === null ){
        this.formData.adPermission = Object.assign({}, {
          newUser: (this.userType.length>0),
          roleIds: Object.assign([], this.tempUserLevels)
        })
      }
      this.$refs.form.validateField('useCondition')
    },
    changeTargetType() {
      this.formData.adLinkObject.title = ''
    }, // 广告图片上传
    uploadSuccess(res) {
      this.$set(this.formData, 'imageUrl', this.replaceImgUrl(res.filePath))
    },
    chooseJump() {
      if (this.formData.targetType === 'GOODS_BIXUAN') {
        this.checkGoods([], 1).then(val => {
          // console.log(val)
          this.formData.adLinkObject.targetValue = val[0].id
          this.formData.adLinkObject.title = val[0].name
        })
      } else if (this.formData.targetType === 'GOODS_BIHUASUAN') {
        this.bhsGoodsChoose().then(val => {
          this.formData.adLinkObject.imageUrl = val[0].imageUrl
          this.formData.adLinkObject.targetType = 'GOODS_BIHUASUAN'
          this.formData.adLinkObject.title = val[0].title
          this.formData.adLinkObject.targetValue = val[0].goodsId
          this.formData.adLinkObject.platform = 'ALI'
        })
      } else if (this.formData.targetType === 'ZERO_BUY_GOOD') {
        this.bhsZeroGoodsChoose().then(val => {
          this.formData.adLinkObject.imageUrl = val[0].imageUrl
          this.formData.adLinkObject.targetType = 'ZERO_BUY_GOOD'
          this.formData.adLinkObject.title = val[0].title
          this.formData.adLinkObject.targetValue = val[0].goodsId
          this.formData.adLinkObject.platform = 'ALI'
        })
      } else if (this.formData.targetType === 'TAG_TOPIC') {
        this.bhsGoodsTag().then(val => {
          this.formData.adLinkObject.targetType = val.type
          this.formData.adLinkObject.title = val.topicName
          this.formData.adLinkObject.platform = 'ALI'
          this.formData.adLinkObject.targetValue = val.topicId
        })
      } else if (this.formData.targetType === 'PLATFORM_BIHUASUAN') {
        this.bhsGoodsPlatForm().then(val => {
          this.formData.adLinkObject.targetType = 'PLATFORM_BIHUASUAN'
          this.formData.adLinkObject.title = val.name
          this.formData.adLinkObject.platform = val.platform
          this.formData.adLinkObject.targetValue = val.platform
        })
      } else if(this.formData.targetType === 'TAOBAO_ACTIVITY') {
        this.bhstaobaoActivity(this.taobaoSelect, 1).then(val => {
          // console.log(val)
          this.formData.adLinkObject.targetType = 'TAOBAO_ACTIVITY'
          this.formData.adLinkObject.title = val[0].activityName
          this.formData.adLinkObject.platform = val[0].platform
          this.formData.adLinkObject.targetValue = val[0].id
          this.formData.gotoWay = val[0].centerPage
          if(val[0].centerPage===0) {
            this.radioDisabled = true
          } else {
            this.radioDisabled = false
          }
          this.taobaoSelect = val
        })
      }
    },
    changeValidate() {
      this.$refs.form.clearValidate()
    },
    setParams() {
      if (this.formData.linkType === 'NONE') {
        this.formData.adLinkObject = null
      } else if (this.formData.linkType === 'LINK_URL') {
        this.formData.adLinkObject.targetValue = this.formData.linkUrl
        this.formData.adLinkObject.targetType = null
      } else if (this.formData.linkType === 'LINK_INNER') {
        if (this.formData.targetType !== 'TAG_TOPIC') {
          this.formData.adLinkObject.targetType = this.formData.targetType
        }

        if (this.formData.targetType === 'GOODS_BIXUAN') {
          if (this.formData.inpageType === 1) {
            this.formData.adLinkObject.fromType = 1
            this.formData.adLinkObject.goodsType = 1
          } else {
            this.formData.adLinkObject.fromType = 3
            this.formData.adLinkObject.goodsType = 2
            this.formData.adLinkObject.packType = 1
          }
        } else if (this.formData.targetType === 'MAKE_MONEY') {
          this.formData.adLinkObject.title = this.formData.title
        } else if (this.formData.targetType === 'TUANYOU') {
          this.formData.adLinkObject.platform = ''
        }
      }
    },
    // 获取碧划算商品id 根据id 查商品列表
    async getBhsGoodId() {
      try {
        const { data } = await getFavorSubjec()
        if (data.length > 0) {
          this.bhsGoodsId = data[0].favoritesId
          return
        }
        this.$message.error('获取商品库失败')
      } catch (error) {
        this.$message.error('获取商品库失败')
        console.log(error)
      }
    },
    save() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let dateTimeRange = this.formData.dateTimeRange
          if (dateTimeRange && dateTimeRange.length > 0) {
            this.formData.startTime = dateTimeRange[0]
            this.formData.endTime = dateTimeRange[1]
          }
          this.setParams()
          // 如果置空了，则需要恢复
          if(this.formData.adPermission === null ) {
            let arr = {
              newUser: (this.userType.length > 0),
              roleIds: Object.assign([], this.tempUserLevels)
            }
            this.formData.adPermission = JSON.parse(JSON.stringify(arr))
          }
          // 如果未勾选
          if(this.formData.BY_USER_NEW == false) {
            this.userType.length = 0
          }
          if(this.formData.BY_USER_TYPE == false) {
            this.formData.adPermission.roleIds.length = 0
          }
          let condition = this.formData.useCondition
          // 判断指定用户项是否传空
          if(this.formData.useCondition === '0'){
            this.formData.adPermission = null
          } else if (this.formData.useCondition === '1') {
            if(this.userType.length > 0) {
              this.formData.adPermission.newUser = true
            }else {
              this.formData.adPermission.newUser = false
            }
            // 如果指定了，但是没选
            if(this.userType.length <= 0 && this.formData.adPermission.roleIds.length <= 0) {
              this.formData.useCondition = ''
            }

          }
          console.log('数据', this.formData)

          try {
            const { data } = await saveAdSetting(this.formData)
            if (data) {
              if (this.id) {
                this.$message.success('新增成功')
              }
              this.$message.success('修改成功')
              this.$router.back()
            }
          } catch (error) {
            this.$message.error('新增失败')
            console.log(error)
          }
        }
      })
    },
    changeBxGoodsType() {
      this.$set(this.formData, 'inpageValue', '')
      this.$set(this.formData, 'inpageName', '')
    },
    beforeUploadAd(file) {
      console.log(file)
      if (!file.type.match('image/')) {
        this.$message.error('请上传图片')
        return false
      }
      if (file.type.match('image/gif')) {
        this.$message.error('请上传png/jpg格式图片')
        return false
      }
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isLt1M
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../../../styles/_mixin.scss';

.use-type-block {
  @include flex;
  margin-left: 24px;
}
.el-checkbox {
  margin-right: 15px;
}
/deep/.el-input-number.is-without-controls .el-input__inner {
  text-align: left !important;
}
</style>
